<?php
namespace Wechat\Controller;

use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
use Think\Model;

class ShopController extends Controller
{
    protected $msg = array('code' => 0, 'msg' => '', 'data' => array());
    protected $_code = 0;
    protected $_msg = '';
    protected $_data = '';

    public function _initialize()
    {
        header("Content-Type:text/html; charset=utf-8");
    }

    protected function outputMsg()
    {
        $msg['code'] = $this->_code;
        $msg['msg'] = $this->_msg;
        if (!empty($this->_data)) {
            $msg['data'] = $this->_data;
        }
        $this->ajaxReturn($msg);
    }

    public function index()
    {
        $token['openid'] = 'o2uRPs44YHtX4NqbqicggQZdRC8g';
        $member = getMember($token['openid'], false);

        #TODO 空的信息入库

        if (!empty($userInfo)) {
            D('Member')->updateMember($member['member_id'], $userInfo['nickname'], $userInfo['sex'], $userInfo['headimgurl']);
        }
        session('member', array('member_id' => $member['member_id'], 'openid' => $member['openid'], 'nickname' => $member['nickname']));
        $this->display();

    }

    public function getRegionList()
    {
        $keyword = I('get.keyword');
        $where = array();
        if ($keyword) {
            $where['region_name'] = array('like', "%{$keyword}%");
        }
        $where['status'] = 1;
        $list = M('Region')->field('region_id,region_name')->where($where)->order('click DESC')->limit(10)->select();

        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $list;
        $this->outputMsg();
    }

    public function getData()
    {
        $member = array('member_id' => 2120, 'openid' => 'o2uRPs44YHtX4NqbqicggQZdRC8g', 'nickname' => '鱼消失了');
        session('member', $member);

        $memberAddress = M('MemberAddress')->where(array('member_id' => $member['member_id'], 'status' => 1))->find();
        if (isset($memberAddress['region_id'])) {
            $region = ['region_id' => $memberAddress['region_id'], 'region_name' => $memberAddress['region_name'], 'first' => 1];
        } else {
            $result = M('Region')->where('status = 1')->order('click DESC, region_id DESC')->find();
            $region = ['region_id' => $result['region_id'], 'region_name' => $result['region_name'], 'first' => 1];
        }

        $date = array();
        $dateList = getMenuDate($region['region_id']);
        if (empty($dateList)) {

        }
        foreach ($dateList as $menuKey => $menu) {
            $current = array();
            $current['menu_date'] = date('m月d日', $menu['menu_date']);
            $current['menu_week'] = getWeek($menu['menu_date']);
            $current['token'] = encrypt($menu['menu_id']);

            $remind = array();
            $goods = array();
            $orderGoods = D('OrderGoods')->getMemberOrderGoods($member['member_id'], $menu['menu_id']);
            if ($orderGoods) {
                $order = array();
                foreach ($orderGoods as $val) {
                    $order[] = $val['goods_name'] . 'x' . $val['goods_num'];
                }
                $current['order'] = $order;
            } else {
                $current['order'] = array();
            }

            $overTime = strtotime(date('Y-m-d ' . getConfig('order_time', false), $menu['menu_date']));
            // 已截止
            if (time() > $overTime) {
                $current['menu_title'] = '已截止';
                $remind['title'] = '当日已全部售罄';
                $week = getWeek($dateList[1]['menu_date']);
                $remind['desc'] = "提前预定{$week}餐品享优惠";

                $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
                if ($menuGoods) {
                    foreach ($menuGoods as $val) {
                        $tmp = array();
                        $tmp['goods_id'] = $val['goods_id'];
                        $tmp['goods_name'] = $val['goods_name'];
                        $tmp['goods_image'] = $val['goods_image'];
                        $tmp['goods_combo'] = $val['goods_combo'];
                        $tmp['market_price'] = $val['market_price'];
                        $tmp['shop_price'] = $val['shop_price'];
                        $tmp['store_id'] = $val['store_id'];
                        $store = getStore($val['store_id']);
                        $tmp['store_logo'] = $store['store_logo'];
                        $tmp['store_slogan'] = $store['store_slogan'];
                        $tmp['goods_storage'] = 0;
                        $goods[] = $tmp;
                    }
                }
            } else {
                // 未截止
                $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
                $allStoreage = 0;
                if ($menuGoods) {
                    foreach ($menuGoods as $val) {
                        $tmp = array();
                        $tmp['goods_id'] = $val['goods_id'];
                        $tmp['goods_name'] = $val['goods_name'];
                        $tmp['goods_image'] = $val['goods_image'];
                        $tmp['goods_combo'] = $val['goods_combo'];
                        $tmp['market_price'] = $val['market_price'];
                        $tmp['shop_price'] = $val['shop_price'];
                        $tmp['store_id'] = $val['store_id'];
                        $store = getStore($val['store_id']);
                        $tmp['store_logo'] = $store['store_logo'];
                        $tmp['store_slogan'] = $store['store_slogan'];

                        $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $val['menu_id'] . '_' . $val['goods_id'];
                        $sellNum = S($key);

                        $surplus = $val['goods_storage'] - $sellNum;
                        $surplus = $surplus <= 0 ? 0 : $surplus;

                        $tmp['goods_storage'] = $surplus;
                        $allStoreage += $surplus;
                        $goods[] = $tmp;
                    }
                    if ($allStoreage <= 0) {
                        $current['menu_title'] = '已售罄';
                        $remind['title'] = '当日已全部售罄';
                        $week = getNextWeek($current['menu_week']);
                        $remind['desc'] = "提前预定{$week}餐品享优惠";
                    } else {
                        if ($menuKey == 0) {
                            $current['menu_title'] = '';
                            $remind['title'] = '距今日订餐结束';
                            $remind['time'] = $overTime;
                            $week = getWeek($dateList[1]['menu_date']);
                            $remind['desc'] = "提前预定{$week}餐品享优惠";
                        }
                    }
                } else {
                    $current['menu_title'] = '已售罄';
                    $remind['title'] = '当日已全部售罄';
                    $week = getNextWeek($current['menu_week']);
                    $remind['desc'] = "提前预定{$week}餐品享优惠";
                }
            }
            $current['goods'] = $goods;
            $current['remind'] = $remind;
            $date[] = $current;
        }

        $comment = D('OrderGoods')->getCommentGoods($member['member_id']);
        $commentID = !empty($comment) ? $comment['id'] : 0;
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['region' => $region, 'menu' => $date, 'comment' => $commentID, 'first' => 1];
        $this->outputMsg();
    }

    public function getCurrentData()
    {
        $regionId = I('post.region_id');
        $menuDate = I('post.menu_date');

        if (empty($regionId)) {
            $this->_code = 10501;
            $this->_msg = '无效的楼宇地区，请重新选择';
            $this->outputMsg();
        }
        $menuDate = strtotime(date('Y') . '-' . str_replace(['月', '日'], ['-', ''], $menuDate));
        if (empty($menuDate)) {
            $this->_code = 10502;
            $this->_msg = '菜单日期不正确';
            $this->outputMsg();
        }

//        $member = session('member');
//        if (empty($member)){
//            $this->_code = 10402;
//            $this->_msg = '获取用户信息失败，请稍后重试';
//            $this->outputMsg();
//        }

        $member['member_id'] = 2120;

        $menu = getTodayMenu($regionId, $menuDate);
        if (empty($menu)) {
            $this->_code = 10503;
            $this->_msg = '获取数据失败';
            $this->outputMsg();
        }

        $current = array();
        $current['menu_date'] = date('m月d日', $menuDate);
        $current['menu_week'] = getWeek($menuDate);
        $current['token'] = encrypt($menu['menu_id']);

        $remind = array();
        $goods = array();
        $orderGoods = D('OrderGoods')->getMemberOrderGoods($member['member_id'], $menu['menu_id']);
        if ($orderGoods) {
            $order = array();
            foreach ($orderGoods as $val) {
                $order[] = $val['goods_name'] . 'x' . $val['goods_num'];
            }
            $current['order'] = $order;
        } else {
            $current['order'] = array();
        }
        $nowTime = strtotime(date('Y-m-d 00:00:00'));
        $nowWeek = getWeek($nowTime);
        if($nowWeek == '周六'){
            $nowTime += 86400 * 2;
        }
        if($nowWeek == '周日'){
            $nowTime += 86400;
        }

        $overTime = strtotime(date('Y-m-d ' . getConfig('order_time', false), $menu['menu_date']));
        // 已截止
        if (time() > $overTime) {
            $current['menu_title'] = '已截止';
            $remind['title'] = '当日已全部售罄';
            $week = getNextWeek($current['menu_week']);
            $remind['desc'] = "提前预定{$week}餐品享优惠";

            $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
            if ($menuGoods) {
                foreach ($menuGoods as $val) {
                    $tmp = array();
                    $tmp['goods_id'] = $val['goods_id'];
                    $tmp['goods_name'] = $val['goods_name'];
                    $tmp['goods_image'] = $val['goods_image'];
                    $tmp['goods_combo'] = $val['goods_combo'];
                    $tmp['market_price'] = $val['market_price'];
                    $tmp['shop_price'] = $val['shop_price'];
                    $tmp['store_id'] = $val['store_id'];
                    $store = getStore($val['store_id']);
                    $tmp['store_logo'] = $store['store_logo'];
                    $tmp['store_slogan'] = $store['store_slogan'];
                    $tmp['goods_storage'] = 0;
                    $goods[] = $tmp;
                }
            }
        } else {
            // 未截止
            $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
            $allStoreage = 0;
            if ($menuGoods) {
                foreach ($menuGoods as $val) {
                    $tmp = array();
                    $tmp['goods_id'] = $val['goods_id'];
                    $tmp['goods_name'] = $val['goods_name'];
                    $tmp['goods_image'] = $val['goods_image'];
                    $tmp['goods_combo'] = $val['goods_combo'];
                    $tmp['market_price'] = $val['market_price'];
                    $tmp['shop_price'] = $val['shop_price'];
                    $tmp['store_id'] = $val['store_id'];
                    $store = getStore($val['store_id']);
                    $tmp['store_logo'] = $store['store_logo'];
                    $tmp['store_slogan'] = $store['store_slogan'];

                    $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $val['menu_id'] . '_' . $val['goods_id'];
                    $sellNum = S($key);

                    $surplus = $val['goods_storage'] - $sellNum;
                    $surplus = $surplus <= 0 ? 0 : $surplus;

                    $tmp['goods_storage'] = $surplus;
                    $allStoreage += $surplus;
                    $goods[] = $tmp;
                }
                if ($allStoreage <= 0) {
                    $current['menu_title'] = '已售罄';
                    $remind['title'] = '当日已全部售罄';
                    $week = getNextWeek($current['menu_week']);
                    $remind['desc'] = "提前预定{$week}餐品享优惠";
                } else {
                    if ($nowTime == $menu['menu_date']) {
                        $current['menu_title'] = '';
                        $remind['title'] = '距今日订餐结束';
                        $remind['time'] = $overTime;
                        $week = getNextWeek($current['menu_week']);
                        $remind['desc'] = "提前预定{$week}餐品享优惠";
                    }
                }
            } else {
                $current['menu_title'] = '已售罄';
                $remind['title'] = '当日已全部售罄';
                $remind['desc'] = "提前预定餐品享优惠";
            }
        }

        $current['goods'] = $goods;
        $current['remind'] = $remind;


        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $current;
        $this->outputMsg();
    }


    public function submitCart()
    {
        $cart = I('post.cart');
        $cart = json_decode($cart, true);

//        $goods1[] = ['goods_id' => 37, 'goods_num' => 2];
//        $goods1[] = ['goods_id' => 44, 'goods_num' => 1];
//        $goods2[] = ['goods_id' => 30, 'goods_num' => 1];
//        $cart = [
//            'region' => ['region_id' => 455, 'region_name' => '百富国际大厦'],
//            'data' => [
//                ['menu_date' => '12月05日', 'menu_week' => '周一', 'token' => "MDAwMDAwMDAwMIOtm5Y", 'goods' => $goods1],
//                ['menu_date' => '12月06日', 'menu_week' => '周二', 'token' => "MDAwMDAwMDAwMIOtm94", 'goods' => $goods2],
//            ]
//        ];

        if (empty($cart['region']['region_id'])) {
            $this->_code = 10101;
            $this->_msg = '无效的楼宇地区，请重新选择';
            $this->outputMsg();
        }

        if (empty($cart['data'])) {
            $this->_code = 10102;
            $this->_msg = '购物车是空的，请添加商品';
            $this->outputMsg();
        }

        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        $coupon = getOptimalCoupon($member['member_id']);

        $order = array();
        $order['region_id'] = $cart['region']['region_id'];
        $order['region_name'] = $cart['region']['region_name'];
        $order['coupon_id'] = isset($coupon['coupon_id']) ? $coupon['coupon_id'] : 0;
        $order['coupon_sn'] = isset($coupon['coupon_sn']) ? $coupon['coupon_sn'] : 0;
        $order['coupon_value'] = isset($coupon['coupon_value']) ? $coupon['coupon_value'] : 0;
        $storageActivity = getConfig('storage_activity');
        $menus = array();
        $discount = 0;
        $goodsAmount = 0;
        $goodsCount = 0;
        foreach ($cart['data'] as $key => $value) {
            $menuId = intval(decrypt($value['token']));
            if ($menuId == 0 || empty($value['goods'])) {
                $this->_code = 10103;
                $this->_msg = '购物车异常，请重新提交购物';
                $this->outputMsg();
            }
            $menu = array();
            $menu['menu_week'] = $value['menu_week'];
            $menu['menu_date'] = $value['menu_date'];
            $menu['menu_id'] = $menuId;
            $price = 0;
            $gPrice = 0;
            foreach ($value['goods'] as $cartGoods) {
                $goods = D('MenuGoods')->getMenuGoods($menuId, $cartGoods['goods_id']);
                if (empty($goods)) {
                    $this->_code = 10105;
                    $this->_msg = '购物车商品下架，请重新选择';
                    $this->outputMsg();
                } else {
                    $goods = $goods[0];
                    $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $menuId . '_' . $cartGoods['goods_id'];
                    $sellNum = S($key);
                    $surplus = $goods['goods_storage'] - $sellNum;
                    if ($surplus <= $cartGoods['goods_num']) {
                        $this->_code = 10104;
                        $this->_msg = $goods['goods_name'] . ' 库存不足，请重新选择';
                        $this->outputMsg();
                    }

                    $surplus = $surplus <= 0 ? 0 : $surplus;
                    if ($storageActivity) {
                        if ($surplus > 0) {
                            if ($surplus <= $goods['storage_one']) {
                                //echo "（{$goods['goods_id']}-最后买）";
                                $gPrice = $goods['sale_one'];
                            } elseif ($surplus > $goods['storage_one'] && $surplus <= $goods['storage_two']) {
                                //echo "（{$goods['goods_id']}-中间买）";
                                $gPrice = $goods['sale_two'];
                            } elseif ($surplus > $goods['storage_two']) {
                                //echo "（{$goods['goods_id']}-最早买）";
                                $gPrice = $goods['sale_three'];
                            } else {
                                $gPrice = 0;
                            }
                        } else {
                            $gPrice = 0;
                        }
                    }
                    $gPrice = $gPrice * $cartGoods['goods_num'];
                    $price += $goods['shop_price'] * $cartGoods['goods_num'];
                    $discount += $gPrice;
                    $goodsCount += $cartGoods['goods_num'];
                    $tGoods = [
                        'goods_id' => $goods['goods_id'],
                        'goods_name' => $goods['goods_name'],
                        'goods_num' => $cartGoods['goods_num'],
                        'market_price' => $goods['market_price'],
                        'shop_price' => $goods['shop_price'],
                        'discount_price' => $gPrice,
                    ];
                    $menu['goods'][] = $tGoods;
                }


            }
            $goodsAmount += $price;
            $menu['goods_price'] = $price;
            $menus[] = $menu;
        }
        $order['menu'] = $menus;
        $order['goods_count'] = $goodsCount;
        $order['goods_amount'] = $goodsAmount;
        $order['discount_amount'] = $discount;
        $orderAmount = $goodsAmount - $order['coupon_value'] - $discount;
        $order['order_amount'] = $orderAmount > 0 ? $orderAmount : 1;
        $order['deliver_time'] = '每天送餐时间' . C('deliver_time');

        S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id'], $order, 86400);
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $order;
        $this->outputMsg();

    }

    public function submitOrder()
    {
        $regionID = I('post.region_id');
        $reciverName = I('post.member_name');
        $reciverPhone = I('post.member_phone');
        $regionName = I('post.region_name');
        $address = I('post.address');

        if (empty($regionID)) {
            $this->_code = 10201;
            $this->_msg = '下单地址填写有误，请重新选择楼宇';
            $this->outputMsg();
        }
        if (empty($reciverName)) {
            $this->_code = 10202;
            $this->_msg = '请填写收货人姓名';
            $this->outputMsg();
        }
        if (empty($reciverPhone)) {
            $this->_code = 10203;
            $this->_msg = '请填写收货人电话';
            $this->outputMsg();
        }
        if (empty($address)) {
            $this->_code = 10204;
            $this->_msg = '请填写收货人地址';
            $this->outputMsg();
        }

        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        vendor('wxpay.WxPay#Api');
        vendor('wxpay.WxPay#JsApiPay');

        $tools = new \JsApiPay();
        $openId = $member['openid'];

        $cacheOrder = S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id']);
        if (empty($cacheOrder)) {
            $this->_code = 10205;
            $this->_msg = '订单超时，请重新选择菜品下单';
            $this->outputMsg();
        }

        $order = array();
        $order['order_sn'] = getOrderSN();
        $order['member_id'] = $member['member_id'];
        $order['menu_id'] = 0;
        $order['goods_num'] = $cacheOrder['goods_count'];
        $order['goods_amount'] = $cacheOrder['goods_amount'];
        $order['order_amount'] = $cacheOrder['order_amount'];
        $order['discount_amount'] = $cacheOrder['discount_amount'];
        $order['pay_id'] = 1;
        $order['pay_code'] = 'wxpay';
        $order['pay_time'] = 0;
        $order['pay_amount'] = $cacheOrder['order_amount'];
        $order['order_state'] = 1;
        $order['store_id'] = 0;
        $order['coupon_id'] = $cacheOrder['coupon_id'];
        $order['coupon_sn'] = $cacheOrder['coupon_sn'];
        $order['create_time'] = NOW_TIME;
        $order['update_time'] = NOW_TIME;

        $input = new \WxPayUnifiedOrder();
        $input->SetBody($order['order_sn']); //描述
        $input->SetOut_trade_no($order['order_sn']);
        $input->SetTotal_fee($order['pay_amount'] * 100); // 订单总金额，单位为分 不能有小数点。
        $input->SetTime_start(date('YmdHis'));
        $input->SetTime_expire(date('YmdHis', time() + 600));
        $input->SetNotify_url(C('SITE_URL') . 'wechat/notify/wxpay_notify');
        $input->SetTrade_type('JSAPI');
        $input->SetOpenid($openId);
        $payOrder = \WxPayApi::unifiedOrder($input);

        $jsApiParameters = $tools->GetJsApiParameters($payOrder);
        $jsApiParameters = json_decode($jsApiParameters);

        if ($jsApiParameters) {
            $model = new Model();
            try {
                $model->startTrans();

                $addressData = array('region_id' => $regionID, 'region_name' => $regionName, 'member_name' => $reciverName, 'member_phone' => $reciverPhone, 'address' => $address);
                $model->table('__MEMBER_ADDRESS__')->where(array('member_id' => $member['member_id'], 'status' => 1))->save($addressData);

                $order['order_id'] = $model->table('__ORDER__')->add($order);
                $allGoods = array();
                foreach ($cacheOrder['menu'] as $menu) {
                    foreach ($menu['goods'] as $val) {
                        $goods = getGoods($val['goods_id']);
                        $og = array();
                        $og['order_id'] = $order['order_id'];
                        $og['order_sn'] = $order['order_sn'];
                        $og['menu_id'] = $menu['menu_id'];
                        $og['store_id'] = $goods['store_id'];
                        $og['member_id'] = $member['member_id'];
                        $og['goods_id'] = $goods['goods_id'];
                        $og['goods_sn'] = $goods['goods_sn'];
                        $og['goods_name'] = $goods['goods_name'];
                        $og['goods_price'] = $goods['shop_price'];
                        $og['goods_num'] = $val['goods_num'];
                        $og['goods_image'] = $goods['goods_image'];
                        $og['goods_pay_price'] = $order['order_sn'];
                        $discount = $val['discount_price'] / $val['goods_num'];
                        $og['goods_pay_price'] = $goods['shop_price'] - $discount;
                        $og['discount_price'] = $discount;
                        $og['create_time'] = NOW_TIME;
                        $og['update_time'] = NOW_TIME;
                        $allGoods[] = $og;
                    }
                }
                $model->table('__ORDER_GOODS__')->addAll($allGoods);

                $common = array();
                $common['order_id'] = $order['order_id'];
                $common['order_sn'] = $order['order_sn'];
                $common['member_id'] = $order['member_id'];
                $common['region_id'] = $regionID;
                $common['region_name'] = $regionName;
                $common['address'] = $address;
                $common['reciver_name'] = $reciverName;
                $common['reciver_phone'] = $reciverPhone;
                $common['deliver_address'] = '';
                $common['create_time'] = NOW_TIME;
                $common['update_time'] = NOW_TIME;
                $model->table('__ORDER_COMMON__')->add($common);

                $model->commit();

                $this->_code = 0;
                $this->_msg = 'ok';
                $this->_data = $jsApiParameters;
                $this->outputMsg();
            } catch (\Exception $e) {
                $model->rollback();
                $this->_code = 10210;
                $this->_msg = '下单失败，请重新购买下单';
                $this->outputMsg();
            }
        } else {
            $this->_code = 10210;
            $this->_msg = '下单失败，请重新购买下单';
            $this->outputMsg();
        }
    }

    public function getComment()
    {
        $commentId = I('get.comment_id');
        if (empty($commentId)) {
            $this->_code = 10300;
            $this->_msg = '请指定评价的菜';
            $this->outputMsg();
        }
        /*
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        */
        $member['member_id'] = 2120;
        $goods = M('OrderGoods')->field('goods_name, goods_image')->where(['id' => $commentId, 'member_id' => $member['member_id']])->order('id ASC')->find();
        if (empty($goods)) {
            $this->_code = 10301;
            $this->_msg = '无效的信息';
            $this->outputMsg();
        }
        $next = M('OrderGoods')->field('goods_name, goods_image')->where("id > {$commentId} AND member_id = {$member['member_id']}")->order('id ASC')->find();
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['goods' => $goods, 'next' => $next ? $next : (object)array()];
        $this->outputMsg();
    }

    public function submitComment()
    {
        $commentId = I('post.comment_id');
        $comment = I('post.comment');
        $star = I('post.star');
        if (empty($commentId)) {
            $this->_code = 10300;
            $this->_msg = '请指定评价的菜';
            $this->outputMsg();
        }
        if (empty($comment)) {
            $this->_code = 10301;
            $this->_msg = '请输入评价内容';
            $this->outputMsg();
        }
        if (empty($star)) {
            $this->_code = 10302;
            $this->_msg = '请选择评价星级';
            $this->outputMsg();
        }
        /*
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        */
        $member['member_id'] = 2120;
        $reuslt = M('OrderGoods')->where(['id' => $commentId, 'member_id' => $member['member_id']])->save(['comment_star' => $star, 'comment' => $comment]);
        if ($reuslt) {
            $this->_code = 0;
            $this->_msg = 'ok';
        } else {
            $this->_code = 10303;
            $this->_msg = '评价失败';
        }
        $this->outputMsg();
    }

    public function getGoodsDetail()
    {
        $goodsId = I('get.goods_id');
        $goods = getGoods($goodsId);
        if (empty($goods)) {
            $this->_code = 10211;
            $this->_msg = '下单失败，请重新购买下单';
            $this->outputMsg();
        }
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $goods;
        $this->outputMsg();
    }

    public function finish()
    {
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        $order = S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id']);
        if (empty($order)) {
            redirect('/wechat/shop/index');
        }
        S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id'], null);
        $this->display();

    }

    public function invite()
    {
        $memberId = I('get.t');
        $memberId = decrypt($memberId);
        if (empty($memberId)) {

        }
        # #TODO 获取微信OPENID 判断添加用户

        #在分别加券

        $this->display();

    }

    public function coupon()
    {
        /*
                $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
                if (!isset($_GET['code'])) {
                    $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                    $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
                    Header("Location: {$url}");
                    exit();
                } else {
                    $token = $auth->getAccessToken('code', $_GET['code']);
                    if (isset($token['errcode'])) {
                        $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                        $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
                        Header("Location: {$url}");
                    }
                }
                $member = getMember($token['openid'], false);
                */
        $member['member_id'] = 2120;
        if (!empty($member)) {
            $coupon = D('MemberCoupon')->getCouponList($member['member_id']);
        } else {
            $coupon = array();
        }
        $coupon = array();
        $this->assign('coupon', $coupon);
        $this->display();
    }

    public function order()
    {
        /*        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
                if (!isset($_GET['code'])) {
                    $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                    $url = $auth->getRequestCodeURL($baseUrl, 'order', 'snsapi_base');
                    Header("Location: {$url}");
                    exit();
                } else {
                    $token = $auth->getAccessToken('code', $_GET['code']);
                    if (isset($token['errcode'])) {
                        $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                        $url = $auth->getRequestCodeURL($baseUrl, 'order', 'snsapi_base');
                        Header("Location: {$url}");
                    }
                }
                $member = getMember($token['openid'], false);*/
        $member['member_id'] = 2120;
        if (!empty($member)) {
            $unfinishOrderList = array();
            $orderList = M('Order')->where(array('member_id' => $member['member_id'], 'order_state' => 2))->limit(50)->getField('order_id, order_sn');
            if (!empty($orderList)) {
                $unfinishOrder = M('OrderGoods')->field('order_id, order_sn, menu_id, goods_name, goods_num')->where(['order_id' => ['in', array_keys($orderList)]])->select();
                foreach ($unfinishOrder as $goods) {
                    $key = $goods['menu_id'] . '_' . $goods['order_id'];
                    $menu = getMenu($goods['menu_id']);
                    $unfinishOrderList[$key]['menu_id'] = $goods['menu_id'];
                    $unfinishOrderList[$key]['menu_date'] = $menu['menu_date'];
                    $unfinishOrderList[$key]['menu_week'] = getWeek($menu['menu_date']);
                    $unfinishOrderList[$key]['order_id'] = $goods['order_id'];
                    $unfinishOrderList[$key]['order_sn'] = $goods['order_sn'];
                    $unfinishOrderList[$key]['goods'][] = ['goods_name' => $goods['goods_name'], 'goods_num' => $goods['goods_num']];
                }
            }

            $finishOrderList = array();
            $orderList = M('Order')->where(array('member_id' => $member['member_id'], 'order_state' => 4))->limit(50)->getField('order_id, order_sn');
            if (!empty($orderList)) {
                $finishOrder = M('OrderGoods')->field('id, order_id, order_sn, menu_id, goods_name, goods_num, goods_image, comment_star')->where(['order_id' => ['in', array_keys($orderList)]])->select();
                foreach ($finishOrder as $goods) {
                    $key = $goods['menu_id'] . '_' . $goods['order_id'];
                    $menu = getMenu($goods['menu_id']);
                    $finishOrderList[$key]['menu_id'] = $goods['menu_id'];
                    $finishOrderList[$key]['menu_date'] = $menu['menu_date'];
                    $finishOrderList[$key]['menu_week'] = getWeek($menu['menu_date']);
                    $finishOrderList[$key]['order_id'] = $goods['order_id'];
                    $finishOrderList[$key]['order_sn'] = $goods['order_sn'];
                    $finishOrderList[$key]['goods'][] = ['id' => $goods['id'], 'goods_name' => $goods['goods_name'], 'goods_num' => $goods['goods_num'], 'comment_star' => $goods['comment_star']];
                }
            }
        } else {
            $finishOrderList = array();
            $unfinishOrderList = array();
        }
        $this->assign('deliverTime', getConfig('deliver_time'));
        $this->assign('finishOrderList', $finishOrderList);
        $this->assign('unfinishOrderList', $unfinishOrderList);
        $this->display();
    }


}